﻿using System.Threading.Tasks;
using AutoMapper;
using CRM.Caches;
using CRM.Services;
using Microsoft.AspNetCore.Mvc;

namespace CRM.Controllers
{
    public class GlobalSearchController : BaseController
    {
        private readonly GlobalSearchService _service;
        private readonly IMapper _mapper;

        public GlobalSearchController(GlobalSearchService service, IMapper mapper)
        {
            _service = service;
            _mapper = mapper;
        }

        /// <summary>
        /// 全球搜索列表页
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<ResultStruct> Index([FromQuery] GlobalSearchService.SearchQuery query)
        {
            if (string.IsNullOrEmpty(query.Keywords))
            {
                return Error(message: "请输入关键词");
            }
            var list = await _service.Search(query);
            if (null == list) return Error(message: _service.Error);

            return Success(new {DomainList = list});
        }

        [HttpGet("[action]")]
        public async Task<ResultStruct> GetInit([FromServices] NationCache nationCache, [FromServices] MyDbContext dbContext)
        {
            var nations = await nationCache.GetTree(dbContext);
            return Success(new {NationList = nations});
        }

        [HttpGet("{id:int}")]
        public async Task<ResultStruct> Info(int id)
        {
            var info = await _service.Info(id);
            if (!string.IsNullOrEmpty(_service.Error)) return Error(message: _service.Error);
            return Success(info);
        }
    }
}